package com.it.data.network.interceptor;

import android.util.Log;

import com.it.common.bean.EventBean;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

import static com.it.common.Constants.MSG_LOGOUT;

/**
 * token拦截器
 */
public class TokenResInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        // 获取原始请求
        Request request = chain.request();
        // 执行请求并获取响应
        Response response = chain.proceed(request);
        // 读取响应体
        String responseBodyString = response.body() != null ? response.body().string() : null;
        Log.d("TokenResInterceptor", "intercept: " + responseBodyString);
        if (responseBodyString.contains("10005")||responseBodyString.contains("10006")) {
            EventBus.getDefault().post(new EventBean(MSG_LOGOUT, ""));
        }

        // 因为 `response.body()` 被消耗掉了，所以需要重新创建一个新的 `ResponseBody`
        // 并使用相同的 `Response` 对象来返回
        ResponseBody newResponseBody = ResponseBody.create(responseBodyString, response.body().contentType());
        return response.newBuilder().body(newResponseBody).build();
    }


}